import * as fs from 'fs';
import * as path from 'path';
import * as moment from 'moment';
import { app, BrowserWindow, Menu, ipcMain, clipboard } from 'electron';
import Server from './servser';
import * as request from 'request';
import { logger } from './logger';

const view: { [key: string]: BrowserWindow } = {};
async function createWindow () {
  // 隐藏菜单栏
  Menu.setApplicationMenu(null);
  // 创建浏览器窗口
  view.login = new BrowserWindow({
    webPreferences: { nodeIntegration: true },
    icon: '../view/img/logo.png',
    width: 346,
    height: 320,

    // 背景透明
    transparent: false,

    // 是否显示边框
    frame: true,

    // 是否可以改变大小
    resizable: false,

    // 开启在任务栏中不显示
    skipTaskbar: false,
  });

  await view.login.loadFile(path.join(__dirname, '../view/html/login.html'));

  ipcMain.on('devLogin', () => {
    view.login.webContents.openDevTools();
  });

  ipcMain.on('login', async (loginEvent, loginData) => {
    const server = new Server(loginData.protocol, loginData.host);
    if (loginData.loginForPin) {
      const success = server.loginForPin(loginData.pin, loginData.encrypted);
      if (!success) {
        loginEvent.sender.send('loginResult', { success: false });
        return;
      }
    } else {
      const success = await server.login(loginData.username, loginData.password);
      if (!success) {
        loginEvent.sender.send('loginResult', { success: false });
        return;
      }
    }
    loginEvent.sender.send('loginResult', { success: true, type: loginData.loginForPin ? 'pin' : 'web' });

    // 登陆成功后隐藏登陆页面
    view.login.hide();

    // if (!loginData.loginForPin) {
    //   await saveFile(`${ server.protocol }://${ server.host }/headImg/${ server.headImg }`);
    // }

    if (loginData.loginForPin) {
      // 通过本地pin登陆的尝试密码登录，这里失败不一定是密码错误，可能是因为网络断开
      server.login(server.username, server.password).then((result) => {
        if (result) {
          // await saveFile(`${ server.protocol }://${ server.host }/headImg/${ server.headImg }`);
          view.app.webContents.send('newLogin', {
            data: server.data,
            headImg: server.headImg,
            nickname: server.nickname,
            version: moment(server.version).format('YYYY-MM-DD HH:mm:ss'),
          });
        }
      })
    }

    if (!view.app) {
      view.app = new BrowserWindow({
        icon: '../view/img/logo.png',
        webPreferences: { nodeIntegration: true },
        height: 610,
        width: 1000,
        minHeight: 610,
        minWidth: 1000,
        // 背景透明
        transparent: false,
        // 是否显示边框
        frame: false,
        // 是否可以改变大小
        resizable: true,
        // 开启在任务栏中不显示
        skipTaskbar: false,
      });
      await view.app.loadURL(path.join(__dirname, '../view/html/index.html'));
    } else {
      view.app.show();
    }
    view.app.webContents.send('init', {
      data: server.data,
      headImg: server.headImg,
      nickname: server.nickname,
      version: moment(server.version).format('YYYY-MM-DD HH:mm:ss'),
    });

    ipcMain.on('update', async (event, data) => {
      const result = await server.update(data);
      event.sender.send('update', {
        success: result.success,
        version: moment(result.version).format('YYYY-MM-DD HH:mm:ss'),
      });
      const encrypted = server.encryptDataForPin();
      event.sender.send('pin', encrypted);
    });

    ipcMain.on('devMain', () => {
      view.app.webContents.openDevTools();
    });

    ipcMain.on('pin', (event, pin) => {
      server.pin = pin;
      const encrypted = server.encryptDataForPin();
      event.sender.send('pin', encrypted);
    });

    ipcMain.on('minimize', () => {
      view.app.minimize();
    });

    ipcMain.on('maximize', () => {
      view.app.maximize();
    });

    ipcMain.on('unmaximize', () => {
      view.app.unmaximize();
    });

    ipcMain.on('quit', () => {
      view.app.hide();
      view.login.show();
    });

    ipcMain.on('close', () => {
      app.quit();
    });

    let timer: NodeJS.Timeout;
    ipcMain.on('copy', async (_event, text) => {
      clearTimeout(timer);
      clipboard.writeText(text);
      timer = setTimeout(() => {
        clipboard.writeText('');
      }, 10000);
    });
  });
}

async function saveFile(url: string) {
  try {
    return new Promise((resolve, reject) => {
      const headImgStream = fs.createWriteStream(path.join(__dirname, `../headImg/${ path.basename(url) }`));
      const imgRequest = request(url);
      imgRequest.on('error', () => {
        reject(url);
      });
      imgRequest.pipe(headImgStream).on('close', resolve);
    });
  } catch (error) {
    logger.error(error);
  }
}

async function init() {
  await app.whenReady();
  await createWindow();
}

init();
